const models = require('../db')
const express = require('express')
const router = express.Router()
const mysql = require('mysql')
const $sql = require('../sqlMap')
// 连接数据库
const conn = mysql.createConnection(models.mysql_config)
// const conn = mysql.createConnection(models.handleDisconnection)
// handleDisconnection()
// const conn = models.handleDisconnection

// conn.connection()


setInterval(function () {
  conn.query('SELECT 1');
  
}, 200)
const jsonWriteAdd = function (res, ret) {
  if (typeof ret === 'undefined') {
    res.json({
      code: '1', msg: '操作失败'
    })
  } else {
    res.json(
      {
        "code":'200',
        "msg":'ok',
      }
    )
  }
}

const jsonWriteShow = function (res, ret) {
  if (typeof ret === 'undefined') {
    res.json({
      code: '1', msg: '操作失败'
    })
  } else {
    res.json(
      {
        code: '200',
         msg: 'ok',
         data:{ret}
      }
      
    )
  }
}

// 接口：增加信息
router.post('/addStu', (req, res) => {
  const sql = $sql.Stu.add
  const params = req.query
  console.log('添加', params)
  conn.query(sql, [params.cs_id, params.channel], function (err, result) {
    if (err) {
      console.log(err)
    }
    if (result) {
      jsonWriteAdd(res, result)
    }
  })
  conn.close;
})

// 接口：查询全部
router.get('/showStu', (req, res) => {
  const sql = $sql.Stu.show
  const params = req.body
  conn.query(sql, [params.stu_Id, params.stu_name, params.stu_sex, params.stu_college, params.stu_class], function (err, result) {
    if (err) {
      console.log(err)
    }
    if (result) {
      jsonWriteShow(res, result)
    }
  })
  conn.close;

})
router.get('/showStus', (req, res) => {
  const sql = $sql.Stu.showlist
  const params = req.query
  console.log('查询',params)
  conn.query(sql, [params.id], function (err, result) {
    if (err) {
      console.log(err)
    }
    if (result) {
      jsonWriteShow(res, result)
    }
  })
  conn.close;

})

// 接口：删除信息
router.delete('/delStu', (req, res) => {
  const sql = $sql.Stu.del
  const params = req.query
  console.log('删除', params)
  conn.query(sql, [params.id], function (err, result) {
    if (err) {
      console.log(err)
    }
    if (result) {
      jsonWriteAdd(res, result)
    }
  })
  conn.close;
})

// 接口：修改信息
router.post('/updateStu', (req, res) => {
  const sql = $sql.Stu.update
  const params = req.query
  console.log('修改', params)
  conn.query(sql, [params.cs_id, params.channel,params.id], function (err, result) {
    if (err) {
      console.log(err)
    }
    if (result) {
      jsonWriteAdd(res, result)
    }
  })
  conn.close;
})

module.exports = router